package mall.dao.impl;

import java.util.List;

import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import mall.bean.Category;
import mall.dao.CategoryDao;
import mall.dao.handler.column.UNDERLINE;

public class CategoryDaoImpl implements CategoryDao {

	@Override
	public void save(Category obj) {

		JdbcTemplate.update("INSERT INTO category (name, is_parent, parent_id, level, sort) VALUES(?,?,?,?,?)",
				obj.getName(), obj.isParent(), obj.getParentId(), obj.getLevel(), obj.getSort());
	}

	@Override
	public void delete(Long id) {
		JdbcTemplate.update("DELETE FROM category WHERE cid = ?", id);
	}

	@Override
	public void update(Category obj) {
		String sql = "UPDATE `category` SET `name`=?, `is_parent`=?, `parent_id`=?, `level`=?, `sort`=? WHERE `cid`=?";
		JdbcTemplate.update(sql, obj.getName(), obj.isParent(), obj.getParentId(), obj.getLevel(), obj.getSort(),
				obj.getCid());
	}

	@Override
	public Category findById(Long id) {
		String sql = "SELECT cid, name, is_parent as parent, parent_id as parentId, level, sort FROM category WHERE cid = ?";
		// 执行查询
		Category category = JdbcTemplate.query(new BeanHandler<Category>(Category.class), sql, id);
		return category;
	}

	@Override
	public List<Category> findListByParent(long parentId) {
		String sql = "SELECT cid, name, is_parent as parent, parent_id as parentId, level, sort FROM category WHERE parent_id = ?";
		return JdbcTemplate.query(new BeanListHandler<Category>(Category.class), sql, parentId);
	}

	@Override
	public long count() {
		return JdbcTemplate.query(new ScalarHandler<Long>(), "SELECT COUNT(cid) FROM category");
	}

	@Override
	public List<Category> findAll() {
		String sql = "SELECT cid, name, is_parent, parent_id as parentId, level, sort FROM category";
		return JdbcTemplate.query(new BeanListHandler<Category>(Category.class, UNDERLINE.PROCESSOR), sql);
	}

	@Override
	public List<Category> findPageList(int skip, int take) {
		String sql = "SELECT cid, name, is_parent, parent_id as parentId, level, sort FROM category ORDER BY cid DESC LIMIT ?, ?";
		return JdbcTemplate.query(new BeanListHandler<Category>(Category.class, UNDERLINE.PROCESSOR), sql, skip, take);
	}
}
